// pages/detail/detail.js
import * as API from "../../utils/config.js"
const app = getApp()
var bookname = ""//声明一个bookname，接收传进来的书名
var idNum = ""//声明一个id，接收传进来的id
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dataList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    bookname = options.bookname;
    idNum = options.id;
    wx.setNavigationBarTitle({
      title: "第" + options.ind + "话"
    });
    // this._getData()//请求数据
    this.pushnew(options);//调用观看记录
  },
  //观看记录
  pushnew(watchObj) {
    var watchRecord = []
    watchRecord = wx.getStorageSync('watchRecord');
    watchRecord.length > 0 ? watchRecord : watchRecord = [];//关键一步，避免get不到的时候为空，类型不是数组调用不了push方法
    var kg = true;
    if (watchRecord.length > 0) {
      watchRecord.forEach((el, index) => {
        if (el.bookname == watchObj.bookname && kg == true) {
          console.log("已存在相同书名，更新记录")
          el= watchObj
          kg = false;
          try {
            wx.setStorageSync('watchRecord', watchRecord)
            } catch (e) {
          }
        } else if (kg == true) {
          console.log("没检测到相同书名，新增")
          watchRecord.unshift(watchObj);
          kg = false;
          try {
            wx.setStorageSync('watchRecord', watchRecord)
          } catch (e) {
          }
        }
      })
    } else {
      watchRecord.push(watchObj);
      try {
        wx.setStorageSync('watchRecord', watchRecord)
      } catch (e) {
      }
    }
  },
  //请求对应章节详细内容
  _getData() {
    wx.request({
      url: API.chapterContent,
      data: {
        "key": API.key,
        "comicName": bookname,
        "id": idNum
      },
      success: (res) => {
        this.setData({
          dataList: res.data.result.imageList,
        })
        console.log(this.data.dataList)
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("初次渲染")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("页面显示")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function (options) {
    console.log("隐藏")
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function (op) {
    console.log(op)
    console.log("卸载")
    // console.log("隐藏添加观看记录")
    // this.pushnew(options);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})